package org.oms.service;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.oms.dao.IBaseDao;
import org.oms.model.pager.Pager;

/**
 * Service层模板基类
 * 
 * @author sunlight
 *
 * @param <T>
 */
public class BaseService<T> implements IBaseService<T> {
	protected IBaseDao<T> dao;

	public IBaseDao<T> getDao() {
		return dao;
	}
	
	@Resource
	public void setDao(IBaseDao<T> dao) {
		this.dao = dao;
	}

	@Override
	public void add(T t) {
		dao.add(t);
	}

	@Override
	public void delete(int id) {
		dao.delete(id);
	}

	@Override
	public void update(T t) {
		dao.update(t);
	}

	@Override
	public T load(int id) {
		return dao.load(id);
	}

	@Override
	public List<T> listAll() {
		return dao.list("from " +getClassName(getClz().getName()));
	}

	@Override
	public Pager<T> findAll() {
		System.out.println(getClz().getName());
		return dao.find("from " + getClassName(getClz().getName()));
	}

	/**
	 * 创建一个Class的对象来获取泛型的class
	 */
	private Class<T> clz;

	@SuppressWarnings("unchecked")
	public Class<T> getClz() {
		if (clz == null) {
			clz = (Class<T>) (((ParameterizedType) this.getClass()
					.getGenericSuperclass()).getActualTypeArguments()[0]);
		}
		return clz;
	}
	
	private String getClassName(String cls){
		return cls.substring(cls.lastIndexOf(".")+1,cls.length());
	}
}
